package etnorservice.etnor_service.controller;



import etnorservice.etnor_service.result.Result;
import etnorservice.etnor_service.service.UserService;
import etnorservice.etnor_service.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;
import java.util.Map;

@RestController
public class VerificationCodeController {

    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private UserService userService;

    @PostMapping("/verificationCode")
    public Result getVerificationCode(@RequestBody Map<String, String> params) {
        String email = params.get("email");

        if (email == null || email.isEmpty()) {
            return Result.error("邮箱不能为空");
        }
       try {
           if(userService.findRoleByEmail(email).size()>0){
               return Result.error("该邮箱已被注册!");
           }
       }catch (Exception e){
           e.printStackTrace();
       }
        try {
            verificationCodeService.sendVerificationCode(email);
            return Result.success(null);
        } catch (MessagingException e) {
            return Result.error("验证码发送失败: " + e.getMessage());
        }
    }
}